<template>
  <view class="container" @touchstart="touchstart" @touchend="touchend">
    <view class="header">
      <view>测试刷题>第一章</view>
      <view>{{ question_index + 1 }}/{{ question.length }}</view>
    </view>
    <!--复选框  选择自动下一题 -->
    <view class="action-btn">
      <u-checkbox-group>
        <u-checkbox v-model="auto.checked" :name="auto.name" @tap="checke">{{ auto.name }}</u-checkbox>
      </u-checkbox-group>
      <!--
      <u-checkbox-group>
        <u-checkbox v-model="showAnswer.checked" :name="showAnswer.name">
          {{
          showAnswer.name
          }}
        </u-checkbox>
      </u-checkbox-group>-->
    </view>
    <view class="content">
      <view class="practice">
        <view class="practice-name">
          <view>({{ this_question['type_value'] }})</view>
          <rich-text :nodes="this_question['name']"></rich-text>
        </view>

        <view class="practice-option">
          <view
            v-for="(option, index) in this_question['option']"
            :key="index"
            class="option-detail"
            @click="this_question['flag'] ? clickOption(option['index']) : ''"
          >
            <view
              class="option avatar"
              :class="[
                getOptionActive(option['index']),
                getQuestionTypeClass(this_question['type']),
              ]"
            >{{ getOptionStr(option['index']) }}</view>
            <view class="option-content">{{ option['content'] }}</view>
          </view>
        </view>

        <view class="practice-about" v-if="showAbout">
          <view class="l-50">
            <text class="practice-about-text">我的答案：</text>
            <text
              class="practice-about-text"
              :class="[isMyRightClass(this_question['my_right'])]"
            >{{ getOptionStr(this_question['my_answer']) }}</text>
          </view>
          <view class="l-50">
            <text class="practice-about-text">参考答案：{{ getRightStr() }}</text>
          </view>
          <view class="l-50" v-if="showExplain">
            <text class="practice-about-text">题目详解：</text>
            <rich-text :nodes="this_question['analysis']"></rich-text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作菜单 -->
    <view class="page-bottom" style="bottom: 134rpx" v-if="showChecked === true">
      <u-button
        style="width: 100%"
        size="default"
        type="primary"
        shape="square"
        plain
        @click="clickChecked()"
      >确定</u-button>
    </view>
    <view class="page-bottom">
      <view>
        <u-button type="primary" shape="circle" plain @click="showPopModel()">答题卡</u-button>
      </view>
      <view v-if="question_index + 1 != 1">
        <u-button type="primary" shape="circle" plain @click="setQuestion(question_index - 1)">上一题</u-button>
      </view>
      <view v-if="question_index + 1 != question.length && showAnswer.checked != false">
        <u-button type="primary" shape="circle" plain @click="setQuestion(question_index + 1)">下一题</u-button>
      </view>
      <view v-if="question.length == question_index + 1">
        <u-button type="primary" shape="circle" plain @click="clickBtn()">提交</u-button>
      </view>
      <!-- <view>
        <u-button
          type="primary"
          shape="circle"
          :plain="isCollect"
          @click="clickShowCollect"
        >{{ changeCollect(this_question['collect']) }}</u-button>
      </view>-->
    </view>
    <!-- 答题卡 -->
    <u-popup v-model="showPop" mode="bottom" round="10" @close="closePop">
      <view class="popup" :style="{ height: scroll_view_height + 'px' }">
        <view class="popup-title">
          <view class="f-1"></view>
          <view class="f-1">答题卡</view>
          <view class="f-1"></view>
        </view>
        <view style="padding: 10rpx">
          <scroll-view
            scroll-y="true"
            class="popup-scroll"
            :style="{ height: scroll_view_height - 40 + 'px' }"
          >
            <view class="popup-content">
              <view
                v-for="(item, index) in question"
                :key="index"
                class="popup-item"
                @click="setQuestion(index)"
              >
                <view class="avatar" :class="[checkQuestionStatus(index)]">{{ index + 1 }}</view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </u-popup>

    <!-- 提交确认弹窗 -->
    <u-modal v-model="showModel" :content="content" @confirm="confirm()" :show-cancel-button="true"></u-modal>

    <!-- 收藏操作菜单 -->
    <u-action-sheet :list="collectList" v-model="showCollect" cancel-text="关闭"></u-action-sheet>

    <!-- 提示消息 -->
    <u-top-tips ref="uTips"></u-top-tips>
  </view>
</template>

<script>
import { getQuestion } from '../../services/kaosi'

export default {
  components: {},
  data() {
    return {
      showPop: false,
      showModel: false,
      showCollect: false,
      content: '确定提交吗？',

      // 自动下一题
      auto: {
        name: '答对自动下一题',
        checked: true,
      },
      // 不作答显示正确答案
      showAnswer: {
        name: '不作答显示正确答案',
        checked: false,
      },

      // 计时使用
      t: '',
      t1: '',
      // 收藏菜单需要处理下数据格式
      collectList: [{ text: '我的收藏', index: 1 }],
      // 没收藏true,收藏false
      isCollect: true,

      phone_width: 300,
      phone_height: 546,
      scroll_view_height: 400,
      options: {},

      question: [
        {
          flag: true,
          analysis: '',
          audios_path: '',
          collect: null,
          exampoint_name: '',
          exampoint_video: '',
          exclusive: 0,
          id: 1,
          is_show_analysis: 0,
          my_answer: '',
          my_right: '',
          name: '题目一',
          name_translate: '',
          not_sure: 0,
          note: null,
          option: [
            {
              audio_path: '',
              content: '选项一',
              content_translate: '',
              id: 1,
              index: 1,
              right: 0,
            },
            {
              audio_path: '',
              content: '选项二',
              content_translate: '',
              id: 2,
              index: 2,
              right: 0,
            },
            {
              audio_path: '',
              content: '选项三',
              content_translate: '',
              id: 3,
              index: 3,
              right: 0,
            },
            {
              audio_path: '',
              content: '选项四',
              content_translate: '',
              id: 4,
              index: 4,
              right: 1,
            },
          ],
          type: 1,
          type_value: '单选',
        },
      ],
      question_index: 0,
      this_question: [],

      showAbout: false,
      showExplain: false,

      showChecked: false,
      checkedEnd: false,

      // 滑动参数
      touchDotX: 0,
      touchDotY: 0,
      time: 0,
      touchMoveX: '',
      touchMoveY: '',
      tmX: '',
      tmY: '',
    }
  },
  methods: {
    checke() {
      this.showAnswer.checked = !this.showAnswer.checked
    },
    showPopModel() {
      this.showPop = true
    },
    closePop() {
      this.showPop = false
    },
    // 选择试题
    setQuestion(index) {
      let data = this.question[index]
      this.this_question = data
      this.showAbout = false
      this.question_index = index
      this.showPop = false

      this.showChecked = false
      this.checkedEnd = false

      // 函数内做了判断，选择了才显示
      this.isShowAbout()
    },
    // 选择转化为A、B、C
    getOptionStr(index) {
      let arr = ['', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']

      let str = ''
      if (index.length > 1) {
        if (index != '' && index != undefined) {
          let str_arr = [...index.toString()]

          for (var o = 0; o < str_arr.length; o++) {
            str += arr[str_arr[o]].toString()
          }
        }
      } else {
        str = arr[index] || ''
      }

      return str
    },
    // 返回自己选择状态对应的class
    isMyRightClass(my_right) {
      if (my_right === true) {
        return 'my-right'
      }
      if (my_right === false) {
        return 'my-wrong'
      }
      return ''
    },
    // 判断当前选择是否选择
    getOptionActive(index) {
      let str = ''
      let option = this.this_question['option']
      for (var o = 0; o < option.length; o++) {
        if (option[o]['class'] && option[o]['index'] == index) {
          str = option[o]['class'] || ''
        }
      }

      return str
    },
    // 返回正确的选项A、B、C
    getRightStr() {
      let str = ''
      let option = this.this_question['option']
      for (var o = 0; o < option.length; o++) {
        if (option[o]['right'] == 1) {
          str += this.getOptionStr(option[o]['index'])
        }
      }

      return str
    },
    // 点击选项(option中的index)
    async clickOption(index) {
      // 回顾历史不允许点击选项
      if (this.options['learn_type'] == 4) {
        console.log('回顾历史不点击~~')
        return false
      }

      console.log(index, '顶顶顶顶顶大大大')
      let q = this.question[this.question_index]
      // 多选时，需手动提交
      if (q['type'] == 2 && this.checkedEnd === false) {
        this.showChecked = true
        await this.updateOption(index)

        await this.$forceUpdate()

        return
      }
      // 修改禁止用
      this.this_question['flag'] = !this.this_question['flag']
      this.updateOption(index)
      this.isRight()
      this.isShowAbout()
      this.autoNextQuestion()

      this.$forceUpdate()
    },
    // 多选的确定
    clickChecked() {
      this.checkedEnd = true
      this.showChecked = false
      this.clickOption()
      // 修改禁止用
      this.this_question['flag'] = !this.this_question['flag']
    },
    // 单选只允许更新一次，多选需要可以取消选中
    updateOption(index) {
      let option = this.this_question['option']
      let type = this.this_question['type']

      for (var o = 0; o < option.length; o++) {
        if (option[o].index == index) {
          if (type == 2) {
            //取消效果
            if (option[o]['class'] && option[o]['class'] == 'active') {
              option[o]['class'] = ''
            } else {
              option[o]['class'] = 'active'
            }
          } else {
            option[o]['class'] = 'active'
          }
        } else {
          if (type != 2) {
            option[o]['class'] = ''
          }
        }
      }

      let q = this.question[this.question_index]
      q['option'] = option
      this.this_question['option'] = option
      this.question[this.question_index] = q
      return true
    },

    // 判断选项是否正确
    isRight() {
      let my_answer = ''
      let right_answer = ''
      let my_right = false

      let option = this.this_question['option']

      for (var o = 0; o < option.length; o++) {
        if (option[o].class && option[o].class == 'active') {
          my_answer += option[o]['index'].toString()
        }

        if (option[o]['right'] == 1) {
          right_answer += option[o]['index'].toString()
        }
      }

      if (right_answer != '' && my_answer == right_answer) {
        my_right = true
      }

      let q = this.question[this.question_index]
      q['my_answer'] = my_answer
      q['my_right'] = my_right

      this.question[this.question_index] = q
      return my_right
    },
    // 是否显示about(点击了或者选择试题时选择过了就显示、或者点击了不作答显示正确答案)|| this.showAnswer.checked == true
    isShowAbout() {
      if (this.this_question['my_answer']) {
        if (this.options['learn_type'] != 2) {
          this.showAbout = true
          this.this_question['is_show_analysis'] == 1
            ? (this.showExplain = true)
            : (this.showExplain = false)
        }
      }
    },
    // 答题卡中检测试题的状态
    checkQuestionStatus(index) {
      let q = this.question[index]
      let status = ''

      if (this.question_index == index) {
        status += ' pop-active'
      }
      if (q['my_right'] === true) {
        status = ' pop-right'
      } else if (q['my_right'] === false) {
        status = ' pop-wrong'
      }

      return status
    },
    // 滑动开始
    touchstart(e) {
      this.touchDotX = e.touches[0].pageX
      this.touchDotY = e.touches[0].pageY
    },
    // 滑动结束
    touchend(e) {
      this.touchMoveX = e.changedTouches[0].pageX
      this.touchMoveY = e.changedTouches[0].pageY
      this.tmX = this.touchMoveX - this.touchDotX
      this.tmY = this.touchMoveY - this.touchDotY
      console.log('time:', this.time)
      if (this.time < 20) {
        let absX = Math.abs(this.tmX)
        let absY = Math.abs(this.tmY)
        console.log(absX)
        if (absX > 2 * absY && absX > 100) {
          if (this.tmX < 0) {
            console.log('左滑=====')
            this.changeQuestion('left')
          } else {
            console.log('右滑=====')
            this.changeQuestion('right')
          }
        }
      }
    },
    // 滑动改变试题
    changeQuestion(f) {
      // 弹出层打开不操作
      if (this.showPop === true) {
        return false
      }

      let index = this.question_index
      if (f == 'left') {
        if (this.question_index >= this.question.length - 1) {
          index = this.question.length - 1
        } else {
          index++
        }
      }

      if (f == 'right') {
        if (this.question_index == 0) {
          index = 0
        } else {
          index--
        }
      }

      this.setQuestion(index)
    },
    autoNextQuestion() {
      if (this.auto['checked'] !== true) {
        console.log('不自动')
        return false
      }

      if (this.this_question['my_right'] !== true) {
        console.log('没答对')
        return false
      }

      // 选择了不作答显示正确答案也不自动
      if (this.showAnswer.checked == true) {
        console.log('直接显示答案')
        return false
      }

      let index = this.question_index
      if (this.question_index >= this.question.length - 1) {
        index = this.question.length - 1
      } else {
        index++
      }

      let that = this
      setTimeout(function () {
        that.setQuestion(index)
      }, 500)
    },

    // 切换试题或者点击收藏时改变按钮的显示
    changeCollect(collect) {
      let str = '收藏'
      let c = true

      if (collect != null && collect['type'] >= 0) {
        let type = this.data['collect_type']

        for (let key in type) {
          if (key == collect['type']) {
            str = '收藏'
            c = false
          }
        }
      }

      this.isCollect = c
      return str
    },
    clickShowCollect() {
      let collect = this.this_question.collect || null

      if (collect != null && collect != undefined) {
        let type = collect['type']
        let list = this.collectList

        for (let key in list) {
          if (type == list[key]['index'] && type >= 0) {
            list[key]['color'] = '#1a76ff'
          } else {
            list[key]['color'] = ''
          }
        }
      }

      this.showCollect = true
    },
    // 保存练习
    confirm() {},
    isSure() {
      let q = this.this_question
      return q['not_sure'] == 1 ? false : true
    },
    // 提交
    clickBtn() {
      let cuoti = 0
      let yitaofenshu = 100 / this.question.length
      console.log(this.question, '我咳咳咳咳咳')
      this.question.forEach((item, index) => {
        if (item['my_right'] == false) {
          cuoti++
        }
      })
      let zuodui = this.question.length - cuoti
      let zonfen = zuodui * yitaofenshu
      console.log(zonfen, '总分为')
      console.log('点击~~')
      // 结束计时
      this.t1 = new Date().getTime()
      let yonshi = this.t1 - this.t
      console.log(this.t, '开始')
      console.log(this.t1, '结束')
      // 将时间差转换为分钟和秒
      const minutes = Math.floor(yonshi / 60000) // 1分钟 = 60秒 * 1000毫秒
      const seconds = Math.floor((yonshi % 60000) / 1000) // 取余得到剩余秒数

      console.log(`做题时间：${minutes} 分钟 ${seconds} 秒`)
      console.log(this.t1 - this.t, '用时')
      uni.navigateTo({
        url:
          '../tijiaojieguo/index?fengshu=' +
          zonfen +
          '&timu=' +
          encodeURIComponent(JSON.stringify(this.question))  +
          '&zuodui=' +
          zuodui +
          '&minutes=' +
          minutes +
          '&seconds=' +
          seconds,
        success: (res) => {
          console.log(res, '跳转成功')
        },
      })
      this.showModel = true
    },
    getQuestionTypeClass(e) {
      var _class = 'radio'
      if (e == 2) {
        _class = 'check'
      }
      console.log(_class, '7777')
      return _class
    },
  },
  async onLoad(e) {
    console.log(e)
    console.log(JSON.parse(e.section), '我看看1116666')
    let item = JSON.parse(e.section)
    let that = this
    uni.getSystemInfo({
      success(res) {
        that.phone_height = res.windowHeight
        that.phone_width = res.windowWidth

        that.scroll_view_height = that.phone_height * 0.7
      },
    })
    let res = await getQuestion(item)
    console.log(res, '题目选择')
    this.question = res.data
    this.setQuestion(0)
    // 启动计时
    this.t = new Date().getTime()
  },
  // onReady() {
  //   this.$refs.uTips.show({
  //     title: '好好学习',
  //     type: 'seccond',
  //     duration: '2300',
  //   })
  // },
}
</script>

<style lang="scss" scoped>
.container {
  height: calc(100vh);

  .header {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 30rpx;

    box-shadow: 10px 10px 5px #f2f2f2;
    font-size: 26rpx;
  }
  .action-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
  .content {
    padding: 30rpx;
    background-color: #fff;

    .practice {
      padding: 0 20rpx 200rpx 20rpx;

      .practice-name {
        font-size: 35rpx;
        font-weight: 600;
        line-height: 50rpx;
        padding-bottom: 20rpx;
      }

      .practice-img {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }

      .option-detail {
        display: flex;
        padding-top: 20rpx;
        padding-bottom: 20rpx;
      }

      .option {
      }
      .option-content {
        flex: 1;
        padding-left: 20rpx;
        line-height: 80rpx;
        font-size: 30rpx;
      }

      .l-50 {
        line-height: 50rpx;
      }
      .practice-about-text {
        font-weight: bold;
        font-size: 28rpx;
      }

      .my-right {
        color: #333;
      }
      .my-wrong {
        color: #e42b00;
      }
    }
  }

  .avatar {
    width: 80rpx;
    height: 80rpx;
    line-height: 72rpx;
    font-size: 1.2em;
    font-weight: 600;
    border-radius: 50%;
    text-align: center;
    color: #989b9f;
    border: 2rpx solid #f2f2f2;
  }
  .active {
    background-color: #1a76ff;
    color: #ffffff;
  }
  .check {
    border-radius: 20rpx;
  }

  /* 底部操作菜单 */
  .page-bottom {
    position: fixed;
    bottom: 30upx;
    z-index: 95;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    width: 80%;
    left: 10%;
    /* bheight: 100upx;
			ackground: rgba(255,255,255,.9);
			box-shadow: 0 0 20upx 0 rgba(0,0,0,.5);
			border-radius: 16upx; */
  }

  .popup {
    margin: 10rpx;

    .popup-title {
      text-align: center;
      padding: 10rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .f-1 {
      flex: 1;
    }

    .popup-content {
      display: flex;
      flex-wrap: wrap;
    }

    .popup-item {
      width: 20%;
      padding: 20rpx;
    }

    .avatar {
      background-color: #f2f2f2;
      line-height: 80rpx;
      border: initial;
    }

    .pop-right {
      color: #fff;
      background-color: #1a76ff;
      line-height: 80rpx;
      border: initial;
    }
    .pop-wrong {
      color: #fff;
      background-color: #e42b00;
      line-height: 80rpx;
      border: initial;
    }
    .pop-active {
      line-height: 72rpx;
      color: #989b9f;
      border: 2rpx solid #1a76ff;
    }
  }
}
</style>
